// 添加文件读取
var fs = require('fs')
var path = require('path')
var childProcess = require('child_process')
var exec = childProcess.exec
var spawn = childProcess.spawn
var spawnSync = childProcess.spawnSync
var env = process.env.BUILD_ENV || "dev";
var buildPath = process.env.BUILD_PATH || "old";
var mirrorCode = '',
  successText = "操作成功",
  failText = "操作失败";


buildPath = '/' + buildPath + '/images/';
console.log('参数env ' + env);
console.log('参数buildPath ' + buildPath);

function getFormatDate() {
  var d = new Date(),
    date = []
  var dateAry = ['getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes']
  for (let i = 0, len = dateAry.length; i < len; i++) {
    let item = dateAry[i],
      num = 0
    if (item === 'getMonth') {
      num = d[item]() + 1
    } else {
      num = d[item]()
    }
    if (num < 10) {
      num = '0' + num
    }
    date.push(num)
  }
  return date.join('')
}

/*
    对git分支进行判断
    sit 镜像只能通过 develop 分支
    stage 镜像只能通过 develop 及 stage/* 分支进行打包
    code 0 成功 1 失败
 */
function checkGitBranch() {
  var info = []
  var a = spawn('git', ['status'])
  a.stdout.on('data', (data) => {
    info = data.toString()
  })
  a.stderr.on('data', err => {
    console.log(`git 检查出错了${err}`);
  })
  a.on('close', code => {
    if (code) {
      console.log(info);
      console.error('git 数据获取失败，请检查git环境或使用手动打包');
      return
    }
    // console.log(info);
    var infoAry = info.split('\n'),
      branchInfo = infoAry[0],
      sitPattern = /(develop)$/img,
      stagePattern = /(develop)|(stage*)|(web*)|(hly*)/img
    if (env == 'sit') {
      // if (sitPattern.test(branchInfo)) {
      npmRunDist()
      // }else{
      //     console.log('uat 环境，只能使用hly-dev分支');
      // }
    } else if (env == 'stage') {
      // if(new Date().getHours()< 17){
      //     console.log('stage环境只能在每天18点之后进行打包');
      //     return
      // }
      console.info(branchInfo)
      if (stagePattern.test(branchInfo)) {
        npmRunDist()
      } else {
        console.error('stage环境，只能使用develop或者stage*分支')
      }
    } else {
      npmRunDist()
    }
  })
}

// npm run dist执行
function npmRunDist() {
  var a = spawn('npm', ['run', 'dist'])
  a.stdout.on('data', function (data) {
    console.log(data.toString())
  })
  a.stderr.on('data', (data) => {
    console.log(`打包进行中: ${data}`);
  });
  a.on('close', (code) => {
    console.log(`子进程退出码：${code}`);
    if (!code) {
      console.log("npm打包完成");
      buildDocker();
    } else {
      console.log("npm 打包失败");
    }
  });
}

// docker镜像文件打包
function buildDocker() {
  var date = getFormatDate()
  console.log('开始打包，请耐心等待。。。')
  mirrorCode = `registry.huilianyi.com/huilianyi/huilianyi-refactoring:${env}-1.0.${date}`
  var a = spawn('docker', ['build', '-t', mirrorCode, '.'])
  a.stdout.on('data', function (data) {
    console.log(data.toString())
  })
  a.stderr.on('data', (err) => {
    console.log(`打包中: ${err}`);
  });
  a.on('close', (code) => {
    console.log(`子进程退出码：${code}`);
    if (!code) {
      console.info(`${successText},docker 镜像打包成功`)
      pushDocker();
    } else {
      console.log(`${failText},docker 镜像打包失败`);
    }
  });
}

// docker镜像上传
function pushDocker() {
  console.log("开始上传 docker镜像，请耐心等待。。。");
  console.log(mirrorCode)
  var b = spawn('docker', ['push', mirrorCode])
  b.stdout.on("data", function (data) {
    console.log(data.toString());
  });
  b.stderr.on("data", err => {
    console.log(`上传镜像失败: ${err}`);
  });
  b.on("close", code => {
    console.log(`子进程退出码：${code}`);
    if (!code) {
      console.info(`${successText},docker 镜像上传成功`)
      console.info(`镜像名称： ${mirrorCode}`)
    } else {
      console.log(`${failText},docker 镜像上传失败`);
    }
  });
}

function main() {
  checkGitBranch()
}

main()
